<template>
  <div class="dashboard-container">
    <github-corner class="github-corner" />
   <el-row :gutter="40" class="panel-group">
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('newVisitis')">
        <div class="card-panel-icon-wrapper icon-people">
          <svg-icon icon-class="peoples" size="4em" class-name="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            访问量
          </div>
          <count-to :start-val="0" :end-val="userView" :duration="2600" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('messages')">
        <div class="card-panel-icon-wrapper icon-message">
           <svg-icon icon-class="edit" size="3rem" class-tagName="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            文章量
          </div>
          <count-to :start-val="0" :end-val="articleCount" :duration="3000" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('purchases')">
        <div class="card-panel-icon-wrapper icon-money">
          <svg-icon icon-class="money" class-name="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            用户量
          </div>
          <count-to :start-val="0" :end-val="userCount" :duration="3200" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('shoppings')">
        <div class="card-panel-icon-wrapper icon-shopping">
          <svg-icon icon-class="shopping" class-name="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            留言量
          </div>
          <count-to :start-val="0" :end-val="messageCount" :duration="3600" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    </el-row>
    <el-row :gutter="40" class="panel-group">
      <el-card style="margin-left:20px;margin-right:20px">
     <div
      class="charts pt-20 chart-container"
      ref="charts"
      style="height: 210px;"
      ></div>
      </el-card>  
    </el-row>
    <el-row :gutter="40" class="panel-group">
      <el-col :span="8"> 
        <el-card>
        <div class="charts" ref="chartRank" @click.prevent="triggerConfetti"  style="height:300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8"> <el-card>
         <div style="height:400px" ref="chartCategory" @click.prevent="ConfettiGenerator"  ></div>
         </el-card></el-col>
      <el-col :span="8"> <el-card>
         <div class="charts" ref="chartTag" @click.prevent="triggerConfetti"  style="height:300px"></div>
        </el-card></el-col>
    </el-row>
  </div>
</template>

<script>
const _ = require("lodash");
import {getArticleCountDate} from '@/api/article'
import {getCategoryListDasboard} from '@/api/category'
import CountTo from 'vue-count-to'
import GithubCorner from '@/components/GithubCorner'
import ConfettiGenerator from 'canvas-confetti';
import {getHotArticle} from '@/api/article'
import {getSite} from '@/api/site'
export default {
  data() {
    return {
      articleCount:0,
      userCount:0,
      messageCount:0,
      userView:0,
      viewCount:0,
      ariticleRank:{},
      category:{},
      myChart: null,
      chartRank:null,
      chartCategory:null,
      chartTag:null,
      articleData: [],
      haveCountArticleArr: [],
      categorys:[],
      archives:[],
      rankArticle:[], //文章排行
      rankedData:[],
    }
  },
  components: {
    CountTo,
    GithubCorner  
  },
  methods: {
    getAll(){
      getSite().then((res)=>{
        if(res.code == 200){
          this.articleCount = res.data.articleCount;
          this.userCount = res.data.userCount;
          this.messageCount = res.data.messageCount;
          this.userView = res.data.userView;
          this.viewCount = res.data.viewCount;
        }
      })
    },
    initCharts(articleData) {
      this.myChart.setOption({
        title: {
          top: 0,
          left: "center",
          text: "今天写文章了吗？",
        },
        tooltip: {
          formatter: function (params) {
            const date = params.value[0]; // 日期
            const data = params.value[1]; // 数据量
            return `${data}篇文章:&nbsp;${date}`;
          },
        },
        visualMap: {
          show: false,
          min: 0,
          max: 4, // 设置最大值为4，超过4的值都使用最后一个颜色
          categories: [0, 1, 2, 3, 4], // 设置颜色的分界
          inRange: {
            color: ["#ebedf0", "#c6e48b", "#7bc96f", "#239a3b", "#1e6823"], //指定颜色为
          },
        },
        calendar: [
          {
            left: "center", // 将日历图放置在画布中央
            range: "2023", // 显示的时间范围为整个2023年
            cellSize: [25, 25], // 每个方块的宽度和高度都为13像素
            splitLine: {
              show: false, // 不显示分割线
            },
            itemStyle: {
              width: "1.88679%", // 每个方块的宽度占据日历图容器的百分比
              color: "transparent", // 设置为透明背景颜色
              height: "15px", // 每个方块的高度为15像素
              color: '#EEEEEE', // 方块的颜色
              borderColor: "#FFF", // 边界颜色
              borderWidth: 4, // 边界宽度
            },
            yearLabel: {
              show: false, // 不显示年份标签
            },
            monthLabel: {
              nameMap: "cn", // 月份名称使用中文
              fontWeight: "lighter", // 月份标签字体样式
              fontSize: 15, // 月份标签字体大小
            },
            dayLabel: {
              show: true, // 显示日期标签
              formatter: "{start}  1st", // 日期标签的格式化字符串
              fontWeight: "lighter", // 日期标签字体样式
              nameMap: ["日", " 一", "二", "三", "四", "五", "六"], // 星期名称映射，第一列是星期日
              fontSize: 12, // 日期标签字体大小
            },
          },
        ],
        series: {
          type: "heatmap",
          center: ["50%", "50%"],
          coordinateSystem: "calendar",
          data: articleData,
          itemStyle: {
            borderRadius: 4, // 设置方块的圆角，可以根据需要调整圆角大小
          },
        },
      });
    },
    initCategory(){
      this.chartCategory.setOption({
        title: { text: "文章分类统计图🎉", left: "center" },
        legend: {
          top: "bottom",
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        series: [
          {
            name: "文章分类数据统计",
            type: "pie",
            radius: [30, 130],
            center: ["50%", "50%"],
            roseType: "area",
            itemStyle: {
              borderRadius: 8,
            },
            data:this.archives,
            // [
            //   { value: 3, name: "系列 1" },
            //   { value: 0, name: "系列 2" },
            //   { value: 0, name: "系列 3" },
            //   { value: 30, name: "rose 4" },
            //   { value: 28, name: "rose 5" },
            //   { value: 26, name: "rose 6" },
            //   { value: 22, name: "rose 7" },
            //   { value: 18, name: "rose 8" },
            // ],
          },
        ],
      });
    },
    initRank(){
       this.myChart.setOption({
          xAxis: {
          data: this.rankArticle
        },
        yAxis: {},
        dataGroupId: '',
        animationDurationUpdate: 500,
        series: {
          type: 'bar',
          id: 'sales',
          data: rankedData,
          universalTransition: {
            enabled: true,
            divideShape: 'clone'
          }
        }
       })
    },
        //将有数据的日期和没有数据的日期合并
    getData(year, frameData) {
      const data = [];
      // 生成一个包含所有可能日期的数组
      for (let month = 1; month <= 12; month++) {
        const lastDay = new Date(year, month, 0).getDate(); // 获取每个月的最后一天
        for (let day = 1; day <= lastDay; day++) {
          const date = `${year}-${String(month).padStart(2, "0")}-${String(
            day
          ).padStart(2, "0")}`;
          data.push([date, 0]); // 默认值为零
        }
      }
      // 合并实际的帧数数据到包含所有日期的数组中
      for (const frame of frameData) {
        const date = frame[0];
        const value = frame[1];

        // 查找并更新对应日期的值
        const dataIndex = data.findIndex((item) => item[0] === date);
        if (dataIndex !== -1) {
          data[dataIndex][1] = value;
        }
      }
      return data;
    },
        //移动端适配
    mobileAdapter() {
      // 获取el-scrollbar组件的实例
      const scrollbar = this.$refs.scrollbar;
      // 设置滚动条的水平方向初始位置为25%（居中）
      const horizontalPercentage = 50; // 水平方向百分比位置
      const horizontalScrollWidth =
        (scrollbar.wrap.scrollWidth - scrollbar.wrap.clientWidth) / 100;
      scrollbar.wrap.scrollLeft = horizontalScrollWidth * horizontalPercentage;
    },
    //获取数据
    async getDateCountData() {
      const year = new Date().getFullYear();
      const res = await getArticleCountDate(year);
      if (res.code == 200) {
        this.articleData = res.data.map((item) => {
          // 使用split方法拆分日期字符串，并获取年月日部分
          const datePart = item.createDate.split("T")[0];
          // 将处理后的日期字符串赋回到对象的createDate属性上
          item.createDate = datePart;
          return item;
        });
        const articleArr = this.articleData.map((item) => [
          item.createDate,
          item.articleCount,
        ]);
        //lodash深拷贝
        this.haveCountArticleArr = _.cloneDeep(articleArr);
        this.articleData = this.getData(year, this.haveCountArticleArr);
      } else {
        this.$message({
          message: "获取每日文章数据失败！",
          type: "error",
        });
      }
    },
    async getCategorys(){
      const res = await  getCategoryListDasboard();
      if(res.code == 200)
      {
      this.categorys = res.data;
      const transformedData = res.data
      .filter(item => item.articleCount !== 0)
      .map(item => ({
        value: item.articleCount,
        name: `${item.categoryName} ${item.articleCount}篇`
      }));
      this.archives = transformedData;
       // 初始化图表放在这里
      this.initCharts();
      }else{
        this.$message({
          type:'error',
          message:'获取分类列表失败！'
        })
      }
    },
    async handleHotArticle(){
      const res = await getHotArticle();
      if(res.code != 200){
        this.$message({type:'error',message:'获取热门文章失败！'})
      }else{
        this.rankArticle = res.data.map(item => item.title);
      }
    }
  },
  async mounted() {
    this.getAll();
    await this.getDateCountData();
    //echarts初始化
    if(this.articleData.length>0)
    {
    this.myChart = this.$echarts.init(this.$refs.charts);
    this.initCharts(this.articleData);
    // 监听窗口大小变化事件
    window.addEventListener("resize", () => {
      // 重新设置图表大小
      this.myChart.resize();
    });
    }else{
      console.log('mei')
    }
    await this.getCategorys();
    this.chartRank = this.$echarts.init(this.$refs.chartRank);
    this.chartCategory = this.$echarts.init(this.$refs.chartCategory);
    this.initCategory();
    window.addEventListener("resize", () => {
      // 重新设置图表大小
      this.chartCategory.resize();
    });
    await this.handleHotArticle();
  },
}
</script>

<style lang="scss" scoped>

.svg-icon {
    width: 4em;
    height: 4em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}
.title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  font-weight: 700;
}

.data-card {
  background: var(--el-bg-color-overlay);
  padding: 1rem;
}

.dashboard-container {
  padding: 32px;
  background: var(--el-bg-color-page);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: var(--el-bg-color-overlay);
    padding: 1rem;
    margin-bottom: 2rem;
  }
}

.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: var(--el-bg-color-overlay);
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-view {
        background: #34bfa3
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-view {
      color: #34bfa3
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: var(--el-text-color-secondary);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}
@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}

@media (max-width:550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>